<template>
  <div class="signature-container">
    <!-- 竖屏提示遮罩 -->
    <div class="rotate-tip-overlay" v-show="showRotateTip">
      <div class="rotate-tip-content">
        <div class="rotate-icon">📱</div>
        <p class="rotate-text">请将设备旋转至横屏模式</p>
        <p class="rotate-subtext">以获得更好的签名体验</p>
      </div>
    </div>

    <!-- 签名界面 -->
    <div class="signature-main" v-show="!showRotateTip">
      <!-- 签名画布 -->
      <div class="canvas-wrapper">
        <canvas class="signature-canvas" ref="signatureCanvas" />

        <!-- 悬浮工具栏 -->
        <div class="floating-toolbar">
          <button class="floating-btn back-btn" @click="goBack" title="返回">
            <span>←</span>
          </button>
          <button class="floating-btn danger" @click="handleClear" title="清除">
            <span>✕</span>
          </button>
          <button class="floating-btn warning" @click="handleUndo" title="撤销">
            <span>↶</span>
          </button>
          <button class="floating-btn success" @click="handleSave" title="保存">
            <span>✓</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import SmoothSignature from "smooth-signature";

export default {
  name: "handWrittenSignature",
  data() {
    return {
      signature: null,
      showRotateTip: false, // 是否显示旋转提示
    };
  },
  mounted() {
    // 检查屏幕方向
    this.checkOrientation();

    // 延迟初始化，确保DOM完全加载
    setTimeout(() => {
      if (!this.showRotateTip) {
        this.initSignature();
      }
    }, 300);

    // 监听窗口大小变化和屏幕方向变化
    window.addEventListener("resize", this.handleResize);
    window.addEventListener("orientationchange", this.handleOrientationChange);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
    window.removeEventListener(
      "orientationchange",
      this.handleOrientationChange
    );
  },
  methods: {
    // 检查屏幕方向
    checkOrientation() {
      // 检查是否为竖屏
      const isPortrait = window.innerHeight > window.innerWidth;
      this.showRotateTip = isPortrait;

      if (!isPortrait) {
        // 横屏时初始化签名
        this.$nextTick(() => {
          setTimeout(() => {
            this.initSignature();
          }, 200);
        });
      }
    },

    // 处理屏幕方向变化
    handleOrientationChange() {
      setTimeout(() => {
        this.checkOrientation();
      }, 300);
    },

    // 处理窗口大小变化
    handleResize() {
      setTimeout(() => {
        this.checkOrientation();
        if (!this.showRotateTip) {
          this.initSignature();
        }
      }, 100);
    },

    // 初始化签名
    initSignature() {
      const canvas = this.$refs.signatureCanvas;
      if (!canvas) {
        console.error("Canvas元素未找到");
        return;
      }

      // 计算画布尺寸
      const canvasWrapper = canvas.parentElement;
      if (!canvasWrapper) {
        console.error("Canvas容器未找到");
        return;
      }

      // 等待DOM完全渲染
      this.$nextTick(() => {
        const rect = canvasWrapper.getBoundingClientRect();
        let width = rect.width - 40; // 减少左右边距
        let height = rect.height - 80; // 考虑上下padding和按钮空间

        // 兼容性处理：如果获取不到尺寸，使用窗口尺寸计算
        if (width <= 0 || height <= 0) {
          width = Math.max(window.innerWidth - 60, 300);
          height = Math.max(window.innerHeight - 160, 200);
        }

        // 确保最小尺寸
        width = Math.max(width, 250);
        height = Math.max(height, 150);

        const options = {
          width: width,
          height: height,
          minWidth: 2,
          maxWidth: 8,
          openSmooth: true,
          color: "#000000",
          // 移除背景色，让画布透明
          // bgColor: "#ffffff",
        };

        // 销毁旧实例
        if (this.signature) {
          try {
            this.signature.clear();
          } catch (e) {
            // 忽略清理错误
          }
          this.signature = null;
        }

        try {
          this.signature = new SmoothSignature(canvas, options);
        } catch (error) {
          console.error("签名组件初始化失败:", error);
        }
      });
    },

    // 清除签名
    handleClear() {
      if (this.signature) {
        this.signature.clear();
      }
    },

    // 撤销
    handleUndo() {
      if (this.signature) {
        this.signature.undo();
      }
    },

    // 生成透明背景的PNG
    getTransparentPNG() {
      if (!this.signature) {
        throw new Error("签名组件未初始化");
      }

      try {
        // 获取原始canvas，用于后处理
        const originalCanvas = this.$refs.signatureCanvas;
        if (!originalCanvas) {
          // 如果找不到canvas，返回库的默认结果
          return this.signature.getPNG();
        }

        // 创建一个新的canvas用于生成透明背景的图片
        const tempCanvas = document.createElement("canvas");
        const tempCtx = tempCanvas.getContext("2d");

        // 设置相同的尺寸
        tempCanvas.width = originalCanvas.width;
        tempCanvas.height = originalCanvas.height;

        // 清除背景（默认就是透明的）
        tempCtx.clearRect(0, 0, tempCanvas.width, tempCanvas.height);

        // 获取原始画布的图像数据
        const originalCtx = originalCanvas.getContext("2d");
        const imageData = originalCtx.getImageData(
          0,
          0,
          originalCanvas.width,
          originalCanvas.height
        );
        const data = imageData.data;

        // 处理像素数据，将白色背景变为透明
        for (let i = 0; i < data.length; i += 4) {
          const r = data[i];
          const g = data[i + 1];
          const b = data[i + 2];

          // 如果是白色或接近白色的像素，设为透明
          // 但保留黑色的签名笔迹
          if (r > 250 && g > 250 && b > 250) {
            data[i + 3] = 0; // 设置alpha为0（透明）
          }
        }

        // 将处理后的数据绘制到新画布
        tempCtx.putImageData(imageData, 0, 0);

        // 返回base64格式的PNG
        return tempCanvas.toDataURL("image/png");
      } catch (error) {
        console.error("生成透明背景签名失败:", error);
        // 如果处理失败，回退到原始方法
        return this.signature.getPNG();
      }
    },

    // 保存签名
    handleSave() {
      if (!this.signature) {
        alert("签名组件未初始化");
        return;
      }

      const isEmpty = this.signature.isEmpty();
      if (isEmpty) {
        alert("请先进行签名");
        return;
      }

      try {
        // 获取画布数据，生成透明背景的PNG
        const pngUrl = this.getTransparentPNG();

        // 生成签名ID和名称
        const timestamp = Date.now();
        const signatureId = `signature_${timestamp}`;
        const now = new Date();
        const dateStr = `${now.getMonth() +
          1}${now.getDate()}${now.getHours()}${now.getMinutes()}`;
        const signatureName = `签名${dateStr}`;

        // 创建签名对象
        const signatureData = {
          id: signatureId,
          name: signatureName,
          image: pngUrl,
          createTime: new Date().toISOString(),
          type: "handwritten",
        };

        // 获取现有的签名列表
        const existingSignatures = JSON.parse(
          localStorage.getItem("userSignatures") || "[]"
        );

        // 添加新签名到列表开头
        existingSignatures.unshift(signatureData);

        // 限制最多保存10个签名
        if (existingSignatures.length > 10) {
          existingSignatures.splice(10);
        }

        // 保存到本地存储
        localStorage.setItem(
          "userSignatures",
          JSON.stringify(existingSignatures)
        );

        alert("签名保存成功！");

        // 保存成功后返回上一页
        setTimeout(() => {
          this.goBack();
        }, 500);
      } catch (error) {
        console.error("保存签名失败:", error);
        alert("保存失败，请重试");
      }
    },

    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },
  },
};
</script>

<style lang="scss" scoped>
.signature-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: #f5f5f5;
  overflow: hidden;
}

// 竖屏提示遮罩
.rotate-tip-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;

  .rotate-tip-content {
    text-align: center;
    color: white;
    padding: 40px 30px;

    .rotate-icon {
      font-size: 80px;
      margin-bottom: 20px;
      animation: rotatePhone 2s ease-in-out infinite;
    }

    .rotate-text {
      font-size: 20px;
      font-weight: 600;
      margin: 0 0 10px 0;
    }

    .rotate-subtext {
      font-size: 16px;
      opacity: 0.8;
      margin: 0 0 30px 0;
    }

    .continue-btn {
      padding: 12px 24px;
      background: rgba(255, 255, 255, 0.2);
      border: 2px solid rgba(255, 255, 255, 0.5);
      border-radius: 25px;
      color: white;
      font-size: 16px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background: rgba(255, 255, 255, 0.3);
        border-color: rgba(255, 255, 255, 0.8);
      }

      &:active {
        transform: scale(0.95);
      }
    }
  }
}

@keyframes rotatePhone {
  0% {
    transform: rotate(0deg);
  }
  25% {
    transform: rotate(-15deg);
  }
  75% {
    transform: rotate(-90deg);
  }
  100% {
    transform: rotate(-90deg);
  }
}

// 签名界面
.signature-main {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-sizing: border-box;

  .canvas-wrapper {
    flex: 1;
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    box-sizing: border-box;
    min-height: 0; // 确保flex布局正常工作

    .signature-canvas {
      border: 2px dashed #dee2e6;
      border-radius: 12px;
      cursor: crosshair;
      touch-action: none;
      // 使用网格背景来显示透明区域，类似PS的透明背景
      background: linear-gradient(45deg, #f0f0f0 25%, transparent 25%),
        linear-gradient(-45deg, #f0f0f0 25%, transparent 25%),
        linear-gradient(45deg, transparent 75%, #f0f0f0 75%),
        linear-gradient(-45deg, transparent 75%, #f0f0f0 75%);
      background-size: 20px 20px;
      background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
      display: block;
      margin: 0 auto;
    }

    .floating-toolbar {
      position: absolute;
      left: 50%;
      bottom: 5px;
      transform: translateX(-50%);
      display: flex;
      flex-direction: row;
      gap: 12px;
      z-index: 10;
      pointer-events: none;

      .floating-btn {
        width: 35px;
        height: 35px;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        transition: all 0.3s ease;
        font-size: 16px;
        font-weight: bold;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        opacity: 0.9;
        pointer-events: all;

        &:hover {
          opacity: 1;
          transform: scale(1.1);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
        }

        &:active {
          transform: scale(0.95);
        }

        &.back-btn {
          background: rgba(108, 117, 125, 0.9);
          color: white;

          &:hover {
            background: rgba(90, 98, 104, 1);
          }
        }

        &.danger {
          background: rgba(220, 53, 69, 0.9);
          color: white;

          &:hover {
            background: rgba(200, 35, 51, 1);
          }
        }

        &.warning {
          background: rgba(253, 126, 20, 0.9);
          color: white;

          &:hover {
            background: rgba(232, 101, 14, 1);
          }
        }

        &.success {
          background: rgba(40, 167, 69, 0.9);
          color: white;

          &:hover {
            background: rgba(33, 136, 56, 1);
          }
        }
      }
    }
  }
}
</style>
